home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / std / c / 105 < prev    next >
Encoding:
Internet Message Format  |  1996-08-06  |  1.2 KB

  1. Path: news.umbc.edu!not-for-mail
  2. From: schlein@umbc.edu (Jonas J. Schlein)
  3. Newsgroups: comp.std.c
  4. Subject: Re: Help, best way to compare doubles
  5. Date: 14 Jan 1996 15:25:42 -0500
  6. Organization: University of Maryland Baltimore County
  7. Message-ID: <4dbos6$o7q@umbc9.umbc.edu>
  8. References: <4d1k09$aqq@mercury.IntNet.net>
  9. NNTP-Posting-Host: f-umbc9.umbc.edu
  10. NNTP-Posting-User: schlein
  11.  
  12. Jeff Tomich <jtomich@IntNet.net> wrote:
  13. |> Having a hard time to figure out a function on how to compare doubles. 
  14. |> Any ideas?
  15.  
  16. I'd go along with what the c.l.c. FAQ has to say about this one:
  17.  
  18. 14.5:    What's a good way to check for "close enough" floating-point
  19.     equality?
  20.  
  21. A:    Since the absolute accuracy of floating point values varies, by
  22.     definition, with their magnitude, the best way of comparing two
  23.     floating point values is to use an accuracy threshold which is
  24.     relative to the magnitude of the numbers being compared.  Rather
  25.     than
  26.  
  27.         double a, b;
  28.         ...
  29.         if(a == b)    /* WRONG */
  30.  
  31.     use something like
  32.  
  33.         #include <math.h>
  34.  
  35.         if(fabs(a - b) <= epsilon * a)
  36.  
  37.     for some suitably-chosen epsilon.
  38.  
  39.     References: Knuth Sec. 4.2.2 pp. 217-8.
  40. -- 
  41. "If it wasn't for C, we would be using BASI, PASAL, and OBOL."
  42.  
  43. Jonas J. Schlein  (schlein@gl.umbc.edu)
  44.